import React, { useState, useEffect } from 'react';
import {
  Card,
  CardContent,
  Typography,
  Grid,
  Box,
  Chip,
  CircularProgress,
  Alert,
  Paper,
} from '@mui/material';
import { TrendingUp, TrendingDown, AccountBalance } from '@mui/icons-material';

interface BillStatistics {
  totalIncome: number;
  totalExpense: number;
  netIncome: number;
  incomeCount: number;
  expenseCount: number;
  totalCount: number;
  incomeByType: Record<string, number>;
  expenseByType: Record<string, number>;
}

interface BillStatisticsProps {
  refreshTrigger?: number;
}

export function BillStatistics({ refreshTrigger = 0 }: BillStatisticsProps) {
  const [statistics, setStatistics] = useState<BillStatistics | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const fetchStatistics = async () => {
    setLoading(true);
    setError(null);
    
    try {
      const token = localStorage.getItem('token');
      
      const response = await fetch('/api/cash/book/statistics', {
        headers: {
          'Authorization': `Bearer ${token}`,
        },
      });
      
      if (!response.ok) {
        throw new Error(`获取统计信息失败: ${response.status}`);
      }
      
      const result = await response.json();
      
      // 处理不同的响应结构
      let statisticsData;
      if (result.success && result.data) {
        statisticsData = result.data;
      } else if (result.success && !result.data) {
        statisticsData = result;
      } else if (result.code === 200) {
        statisticsData = result.data || result;
      } else {
        statisticsData = result;
      }
      
      // 验证数据结构
      if (statisticsData && typeof statisticsData === 'object') {
        setStatistics(statisticsData);
      } else {
        throw new Error('返回的统计数据格式不正确');
      }
    } catch (err) {
      console.error('Statistics fetch error:', err);
      setError(err instanceof Error ? err.message : '获取统计信息失败');
      // 设置默认统计数据，确保页面能正常渲染
      setStatistics({
        totalIncome: 0,
        totalExpense: 0,
        netIncome: 0,
        incomeCount: 0,
        expenseCount: 0,
        totalCount: 0,
        incomeByType: {},
        expenseByType: {},
      });
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchStatistics();
  }, [refreshTrigger]);

  // 使用默认数据，确保组件始终能渲染
  const defaultStatistics: BillStatistics = {
    totalIncome: 0,
    totalExpense: 0,
    netIncome: 0,
    incomeCount: 0,
    expenseCount: 0,
    totalCount: 0,
    incomeByType: {},
    expenseByType: {},
  };

  const currentStatistics = statistics || defaultStatistics;

  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat('zh-CN', {
      style: 'currency',
      currency: 'CNY',
    }).format(amount);
  };

  // 安全地获取收入类型分布
  const incomeByType = currentStatistics.incomeByType || {};
  const expenseByType = currentStatistics.expenseByType || {};

  // 防止除零错误
  const totalAmount = currentStatistics.totalIncome + currentStatistics.totalExpense;
  const incomePercentage = totalAmount > 0 ? ((currentStatistics.totalIncome / totalAmount) * 100).toFixed(1) : '0.0';
  const expensePercentage = totalAmount > 0 ? ((currentStatistics.totalExpense / totalAmount) * 100).toFixed(1) : '0.0';

  return (
    <Grid container spacing={2}>
      {/* 错误提示 */}
      {error && (
        <Grid item xs={12}>
          <Alert severity="warning" sx={{ mb: 2 }}>
            统计信息加载失败，显示默认数据。错误: {error}
          </Alert>
        </Grid>
      )}

      {/* 加载指示器 */}
      {loading && (
        <Grid item xs={12}>
          <Box display="flex" justifyContent="center" p={2}>
            <CircularProgress size={24} />
            <Typography variant="body2" sx={{ ml: 1 }}>
              正在加载统计信息...
            </Typography>
          </Box>
        </Grid>
      )}

      {/* 总收入 */}
      <Grid item xs={12} sm={6} md={3}>
        <Card sx={{ bgcolor: 'success.light', color: 'white' }}>
          <CardContent>
            <Box display="flex" alignItems="center" gap={1}>
              <TrendingUp />
              <Typography variant="h6">总收入</Typography>
            </Box>
            <Typography variant="h4" sx={{ mt: 1 }}>
              {formatCurrency(currentStatistics.totalIncome)}
            </Typography>
            <Typography variant="body2" sx={{ mt: 1 }}>
              {currentStatistics.incomeCount} 笔收入
            </Typography>
          </CardContent>
        </Card>
      </Grid>

      {/* 总支出 */}
      <Grid item xs={12} sm={6} md={3}>
        <Card sx={{ bgcolor: 'error.light', color: 'white' }}>
          <CardContent>
            <Box display="flex" alignItems="center" gap={1}>
              <TrendingDown />
              <Typography variant="h6">总支出</Typography>
            </Box>
            <Typography variant="h4" sx={{ mt: 1 }}>
              {formatCurrency(currentStatistics.totalExpense)}
            </Typography>
            <Typography variant="body2" sx={{ mt: 1 }}>
              {currentStatistics.expenseCount} 笔支出
            </Typography>
          </CardContent>
        </Card>
      </Grid>

      {/* 净收入 */}
      <Grid item xs={12} sm={6} md={3}>
        <Card sx={{ 
          bgcolor: currentStatistics.netIncome >= 0 ? 'primary.light' : 'warning.light', 
          color: 'white' 
        }}>
          <CardContent>
            <Box display="flex" alignItems="center" gap={1}>
              <AccountBalance />
              <Typography variant="h6">净收入</Typography>
            </Box>
            <Typography variant="h4" sx={{ mt: 1 }}>
              {formatCurrency(currentStatistics.netIncome)}
            </Typography>
            <Typography variant="body2" sx={{ mt: 1 }}>
              {currentStatistics.totalCount} 笔交易
            </Typography>
          </CardContent>
        </Card>
      </Grid>

      {/* 收支比例 */}
      <Grid item xs={12} sm={6} md={3}>
        <Card>
          <CardContent>
            <Typography variant="h6" gutterBottom>
              收支比例
            </Typography>
            <Box display="flex" flexDirection="column" gap={1}>
              <Box display="flex" justifyContent="space-between" alignItems="center">
                <Typography variant="body2">收入</Typography>
                <Chip 
                  label={`${incomePercentage}%`}
                  color="success"
                  size="small"
                />
              </Box>
              <Box display="flex" justifyContent="space-between" alignItems="center">
                <Typography variant="body2">支出</Typography>
                <Chip 
                  label={`${expensePercentage}%`}
                  color="error"
                  size="small"
                />
              </Box>
            </Box>
          </CardContent>
        </Card>
      </Grid>

      {/* 收入类型分布 */}
      <Grid item xs={12} md={6}>
        <Paper sx={{ p: 2 }}>
          <Typography variant="h6" gutterBottom>
            收入类型分布
          </Typography>
          <Box display="flex" flexWrap="wrap" gap={1}>
            {Object.entries(incomeByType || {}).map(([type, amount]) => (
              <Chip
                key={type}
                label={`${type}: ${formatCurrency(amount)}`}
                color="success"
                variant="outlined"
                size="small"
              />
            ))}
            {Object.keys(incomeByType || {}).length === 0 && (
              <Typography variant="body2" color="textSecondary">
                暂无收入记录
              </Typography>
            )}
          </Box>
        </Paper>
      </Grid>

      {/* 支出类型分布 */}
      <Grid item xs={12} md={6}>
        <Paper sx={{ p: 2 }}>
          <Typography variant="h6" gutterBottom>
            支出类型分布
          </Typography>
          <Box display="flex" flexWrap="wrap" gap={1}>
            {Object.entries(expenseByType || {}).map(([type, amount]) => (
              <Chip
                key={type}
                label={`${type}: ${formatCurrency(amount)}`}
                color="error"
                variant="outlined"
                size="small"
              />
            ))}
            {Object.keys(expenseByType || {}).length === 0 && (
              <Typography variant="body2" color="textSecondary">
                暂无支出记录
              </Typography>
            )}
          </Box>
        </Paper>
      </Grid>
    </Grid>
  );
}
